const express = require("express");
const router = express.Router();
const userCtrl = require("../../controllers/user");

router.get("/", (req, res) => {
  res.json(userCtrl.getAllUsers());
});

router.get("/:id", (req, res) => {
  const userId = req.params.id;
  if (userId === undefined || isNaN(parseInt(userId))) {
    res.status(400).json({
      error: "Invalid user id",
    });
  }
  const u = userCtrl.getUserById(userId);
  if (u) {
    res.json(u);
  } else {
    res.status(404).json({
      error: "User not found",
    });
  }
});
// add user
router.post('/', (req, res) => {  
  const userInfo = req.body;
  if (userInfo.name === undefined) {
    res.status(400).json({
      error: 'Missing name'
    });
  }
  const u = userCtrl.add(userInfo.name);
  res.json(u);
});

exports = module.exports = router;